from time import sleep

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver

from uitls.file_util import FileUtil
from uitls.logs_util import logger


class BasePage:
    _base_url = ''

    def __init__(self, driver: WebDriver = None):
        # 判断页面接收的driver是否存在，存在则继续使用，如果没有则实例化一个driver
        if driver is not None:
            self.driver = driver
        else:
            self.driver = webdriver.Chrome()
        # 添加隐式等待
        self.driver.implicitly_wait(3)
        # 判断_Base_url是否存在，
        if self._base_url:
            logger.info(self._base_url)
            self.driver.get(self._base_url)
        # 访问之后因为没有登录，所以需要添加cookie到当前页面的session会话中获得权限
        cookies = FileUtil.read_yaml('cookies')
        for cookie in cookies:
            if 'expiry' in cookie:
                del cookie['expiry']
            self.driver.add_cookie(cookie)
        sleep(3)
        # 添加cookie后刷新页面
        self.driver.refresh()

    def find(self, by, locator):
        if locator is None:
            return self.driver.find_element(**by)
        else:
            return self.driver.find_element(by, locator)
